package com.github.aloxc.plugin;

import org.apache.commons.io.FileUtils;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.io.File;

public class JSTesterCallFunctions {
    public static void main(String[] args) {
        Log.log(decode2("lastName\u003dPotter"));
        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine nashorn = scriptEngineManager.getEngineByName("nashorn");
        try {

//            URL resource = JSTesterCallFunctions.class.getResource(fileName);
//            new File(resource.getFile());
            File jf = new File("d:/format.js");
            boolean exists = jf.exists();
            String format = FileUtils.readFileToString(jf, "utf-8");
            File cf = new File("d:/content.js");
            String content = FileUtils.readFileToString(cf, "utf-8");
            nashorn.eval(format);
            String result = (String) ((Invocable) nashorn).invokeFunction("js_beautify", content,2,' '); //执行
//            for (int i = 0; i < args.length; i++) {
//                File file = new File(args[i]).getAbsoluteFile();
//                System.out.println("args[" + i + "] is" + file);
//                if (file.isFile()) {
//                    String strJSName = args[i];// For Jar
//                    nashorn.eval(new FileReader(strJSName));
//                    Object eval = nashorn.eval("make('" + strJSName + "')");// 传递参数strJSName到JS脚本
//			else{
//                        System.out.println("Java运行命令参数非法，请检查！");
//                    }
//                }
//            } catch(ScriptException | FileNotFoundException e){
//                System.out.println("Error executing script: " + e.getMessage());
//            }
        }catch (Exception e){

        }
    }
    public static String decode2( String s )
    {
        StringBuilder sb = new StringBuilder( s.length() );
        char[] chars = s.toCharArray();
        for( int i = 0; i < chars.length; i++ )
        {
            char c = chars[i];
            if( c == '\\' && chars[i + 1] == 'u')
            {
                char cc = 0;
                for( int j = 0; j < 4; j++ )
                {
                    char ch = Character.toLowerCase( chars[i + 2 + j] );
                    if( '0' <= ch && ch <= '9' || 'a' <= ch && ch <= 'f' )
                    {
                        cc |= ( Character.digit( ch, 16 ) << ( 3 - j ) * 4 );
                    }else
                    {
                        cc = 0;
                        break;
                    }
                }
                if ( cc > 0 )
                {
                    i += 5;
                    sb.append( cc );
                    continue;
                }
            }
            sb.append( c );
        }
        return sb.toString();
    }

}

